//
//  ST_MobilePhoneStepDispatcher.swift
//  btvideo
//
//  Created by mac on 2021/1/13.
//  Copyright © 2021 JarvanZhang. All rights reserved.
//

import UIKit
import SwiftyJSON

enum MobilePhoneNumberViewStep {
    case login,registerBind,bind
}

class ST_MobilePhoneStepDispatcher: NSObject {

    static let shared = ST_MobilePhoneStepDispatcher()
    
    fileprivate weak var sy_auth_page_v_c:UIViewController?
    
    fileprivate weak var hud_controller:UIViewController?
    
    fileprivate weak var fromController:UIViewController?
    
    fileprivate(set) var step_state = MobilePhoneNumberViewStep.login
    
    
    fileprivate(set) var from_shan_yan = false
    
    private override init() {
        super.init()
    }
    
    fileprivate func push_phone_number_controller(){
        
        let vc = ST_BTPhoneNumberController()
        
        vc.bind_phone_number = true
        
        if let nav = fromController as? UINavigationController{
            
            nav.pushViewController(vc)
            
            self.hud_controller = nav
            
        }else{
            
            let loginNav = UINavigationController.init(rootViewController: vc)
            
            loginNav.navigationBar.isHidden = true
            
            loginNav.interactivePopGestureRecognizer?.isEnabled = false
            
            self.hud_controller = loginNav
            
            GlobalPresent(toController: loginNav)
            
        }
    }
    
    
//    MARK: - Public Method
    func start_phone_number(state:MobilePhoneNumberViewStep,controller:UIViewController?)  {
        
        self.step_state = state
        
        self.fromController = controller
        
        self.hud_controller = controller
        
        self.hud_controller?.show_indeterminate_h_u_d()
        
        CLShanYanSDKManager.preGetPhonenumber { (result) in
            
            main_thread_execute {
                self.hud_controller?.hidden_indeterminate_h_u_d()
            }
            
            if let error = result.error{
                
             print("闪验失败1111：",error)
                main_thread_execute {
                    
                    self.push_phone_number_controller()
                }
            }else{
             
                main_thread_execute {
                    
                    guard let vc = self.fromController else {
                        return
                    }
                    
                    let uiConfigure = ST_ShanYanConfigureMaker(delegate: self).configure_bind_phone_number_style_yin_ke(configureInstance: CLUIConfigure())
                    
//                        .configure_style_yin_ke(configureInstance: CLUIConfigure())
                    
                    uiConfigure.viewController = vc
                    
                    CLShanYanSDKManager.setCLShanYanSDKManagerDelegate(self)
                    
                    CLShanYanSDKManager.quickAuthLogin(with: uiConfigure, openLoginAuthListener: self.openLoginAuthListener(complete:),oneKeyLoginListener:self.oneKeyLoginListener(complete:))
                }
            }
        }
    }
    
    func check_phone_number(_ number:String,captcha:String) {
      
            self.hud_controller?.show_indeterminate_h_u_d()
            
            JVrequest(PH.checkPhoneNumberApi,parameters: ["phone":number,"code":captcha],success: { (json) in
            
                self.hud_controller?.hidden_indeterminate_h_u_d()
                
                    
                ST_BTUserInfoManager.shared.additional_attributes?.phoneBound = true
                    
                    self.hud_controller?.toast(text: "绑定成功 可以继续操作啦")
                    
                    main_thread_execute(afterDelay: 2) {
                        self.fromController?.dismiss(animated: true, completion: nil)
                    }
               
            }, failure: { (code, err) in
                
                self.hud_controller?.toast(text: err)
            })

        
        
        
    }
}

//MARK: - Shanyan Delegate
extension ST_MobilePhoneStepDispatcher:CLShanYanSDKManagerDelegate,ST_ShanYanConfigureMakerDelegate{
    
    
    func clShanYanSDKManagerAuthPageCompleteViewDidLoad(_ authPageVC: UIViewController, currentTelecom telecom: String?, object: NSObject?, userInfo: [AnyHashable : Any]? = nil) {
        
        sy_auth_page_v_c = authPageVC
        
    }
    
    
    func clShanYanSDKManagerAuthPageCompleteViewWillAppear(_ authPageVC: UIViewController, currentTelecom telecom: String?, object: NSObject?, userInfo: [AnyHashable : Any]? = nil) {
        
        from_shan_yan = true
        
        print("闪验ViewWillAppear")
        //ST_BTGlobalDataCenter.shared.beginLogPageView("LoginCurrentlyOrReceiveMsg")
    }
    
    
    func openLoginAuthListener(complete: CLCompleteResult){
        
//        DispatchQueue.main.async {
//            HUD.hide()
//        }
        
        let error = complete.error as NSError?
        guard error == nil else{
            let msg = String(complete.code)
            let message = complete.message ?? ""
            var errorString = ""
            if error!.userInfo.count > 0 {
               errorString = String(format: "%@", JSON(error!.userInfo).dictionaryObject ?? "")
            }
            
            print(#function,#line,msg,message,errorString)
            
//            DispatchQueue.main.async {
//                HUD.flash(.label("\(msg)\(message)\n\(errorString)"), delay: 2.5)
//            }
            
            print("闪验打开成功")
            
            return
        }
    
        print(#function,#line,complete.code,complete.message ?? "")
    }
    func oneKeyLoginListener(complete: CLCompleteResult){
        
//        DispatchQueue.main.async {
//            HUD.hide()
//        }
        /*
        let error = complete.error as NSError?
        guard error == nil else{
            let msg = String(complete.code)
            let message = complete.message ?? ""
            var errorString = ""
            if error!.userInfo.count > 0 {
                errorString = String(format: "%@", JSON(error!.userInfo).dictionaryObject ?? "")
            }
            print(#function,#line,msg,message,errorString)
            
            return
        }*/
        
        
        print(#function,#line,complete.code,complete.message ?? "")
        
        guard let token = complete.data?["token"] as? String else {
            return
        }

        main_thread_execute {
            
            self.loginUseShanyan(sToken: token)
        }
        
        
        
    }
    
    fileprivate func loginUseShanyan(sToken:String)  {
        
        let param = ["open_id":sToken,"type":4] as [String : Any]
            
        PlayFeedBack()
        
        JVrequest(PH.bindShanyanMobileApi,parameters:param, success: { (json) in
            
            let dataJson = json["data"]
          
            ST_BTUserInfoManager.shared.additional_attributes?.phoneBound = true
            
            print("闪验绑定返回信息:",dataJson)
            //ST_BTGlobalDataCenter.shared.endLogPageView("LoginCurrentlyOrReceiveMsg")
            
            self.sy_auth_page_v_c?.dismiss(animated: false, completion: {
                self.hud_controller?.toast(text: "绑定成功 可以继续操作啦")
                
                main_thread_execute(afterDelay: 2) {
                    self.fromController?.dismiss(animated: true, completion: nil)
                }
            })
            
            /*
            CLShanYanSDKManager.finishAuthControllerCompletion {
                
                self.hud_controller?.toast(text: "绑定成功 可以继续操作啦")
                
                main_thread_execute(afterDelay: 2) {
                    self.fromController?.dismiss(animated: true, completion: nil)
                }
          
            }
            */
        }, failure: { (code, err) in
            
            print("闪验绑定信息错误：",err)
            
            if let subItems = self.sy_auth_page_v_c?.view.subviews{
                subItems.last?.removeFromSuperview()
            }
            
            
            self.sy_auth_page_v_c?.toast(text: err)
            
        })
        
    }
    
    func shanYanConfigureOtherWayClick(sender: UIButton){
        
        //ST_BTGlobalDataCenter.shared.endLogPageView("LoginCurrentlyOrReceiveMsg")
//        CLShanYanSDKManager.finishAuthControllerCompletion {
//
//            self.push_phone_number_controller()
//        }
        
        self.sy_auth_page_v_c?.dismiss(animated: false, completion: {
            
            self.push_phone_number_controller()
        })
    }
    
    func custom_nav_left_item_click(sender: UIButton){
        
    }
    
}
